<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('collectionManagement.amountBreakdown.recallDate')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.currentPeriodRepayDate')">
          <el-date-picker
            v-model="currentTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.stage')">
          <el-select v-model="searchForm.stageId" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.stage')">
            <el-option
              v-for="item in allStage"
              :key="`stage${item.id}`"
              :label="item.phaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.overdueDay')">
          <el-col :span="11">
            <el-input
              v-model="searchForm.overdueDayStart"
              :controls="false"
              :max="10000000000000"
              :placeholder="$t('financeModule.list.days')"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="2" style="text-align: center">~</el-col>
          <el-col :span="11">
            <el-input
              v-model="searchForm.overdueDayEnd"
              :controls="false"
              :max="10000000000000"
              :placeholder="$t('financeModule.list.days')"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.loanProductType')">
          <el-select v-model="searchForm.loanProductType" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('collectionManagement.amountBreakdown.productType')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.orderNo')">
          <el-input
            v-model="searchForm.orderNo"
            clearable
            :maxlength="50"
            :placeholder="$t('common.input')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.phoneNumber')">
          <el-input
            v-model="searchForm.phoneNumber"
            clearable
            :maxlength="50"
            :placeholder="$t('common.input')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.dealStatus')">
          <el-select v-model="searchForm.dealStatus" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('collectionManagement.amountBreakdown.transactionStatus')"
              :key="`dealStatus${item.value}`"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.firm')">
          <el-select v-model="searchForm.firmId" clearable :placeholder="$t('collectionManagement.report.prompt.company')">
            <el-option
              v-for="item in allFirm"
              :key="`firm${item.id}`"
              :label="item['firmName']"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.group')">
          <el-select v-model="searchForm.groupId" clearable :placeholder="$t('collectionManagement.management.prompt.group')">
            <el-option-group
              v-for="group in allGroup"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="`group${item.value}`"
                :label="item.label"
                :value="item.value"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.amountBreakdown.staffName')">
          <el-input
            v-model="searchForm.staffName"
            clearable
            :maxlength="50"
            :placeholder="$t('common.input')"
          />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          prop="staffName"
          :label="tableText['staffName']"
          min-width="150"
        />
        <el-table-column
          fixed="left"
          prop="groupName"
          :label="tableText['group']"
          min-width="150"
        />
        <el-table-column
          prop="firmName"
          :label="tableText['firm']"
          min-width="150"
        />
        <el-table-column
          prop="amount"
          :label="tableText['amount']"
          min-width="150"
        />
        <el-table-column
          prop="createTime"
          :label="tableText['recallDate']"
          min-width="170"
        />
        <el-table-column
          prop="serialNumber"
          :label="tableText['serialNumber']"
          min-width="150"
        />
        <el-table-column
          prop="transactionStatus"
          :label="tableText['dealStatus']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['transactionStatus'] !== null ? setValue(scope.row['transactionStatus'], 'collectionManagement.amountBreakdown.transactionStatus') : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="dueDays"
          :label="tableText['overdueDay']"
          min-width="150"
        />
        <el-table-column
          prop="stageName"
          :label="tableText['stage']"
          min-width="150"
        />
        <el-table-column
          prop="orderStatus"
          :label="tableText['orderStatus']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['orderStatus'] !== null ? setValue(scope.row['orderStatus'], 'orderList.allList.orderStatusEnum') : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNo"
          :label="tableText['orderNo']"
          min-width="150"
        />
        <el-table-column
          prop="userPhone"
          :label="tableText['phoneNumber']"
          min-width="150"
        />
        <el-table-column
          prop="orderType"
          :label="tableText['loanProductType']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['orderType'] !== null ? setValue(scope.row['orderType'], 'collectionManagement.amountBreakdown.productType') : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="loanMoney"
          :label="tableText['loanMoney']"
          min-width="150"
        />
        <el-table-column
          prop="loanDays"
          :label="tableText['limit']"
          min-width="150"
        />
        <el-table-column
          prop="currentPeriod"
          :label="tableText['period']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['currentPeriod'] }} / {{ scope.row['totalPeriod'] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realCurrentRepay"
          :label="tableText['repayMoneyShould']"
          min-width="180"
        />
        <el-table-column
          prop="applyMoney"
          :label="tableText['principal']"
          min-width="150"
        />
        <el-table-column
          prop="interestMoney"
          :label="tableText['interest']"
          min-width="150"
        />
        <el-table-column
          prop="otherServiceCharge"
          :label="tableText['serviceFee']"
          min-width="180"
        />
        <el-table-column
          prop="overDueFine"
          :label="tableText['overdueFee']"
          min-width="150"
        />
        <el-table-column
          prop="planRepaymentDate"
          :label="tableText['RepayTimeShould']"
          min-width="170"
        />
        <el-table-column
          prop="realRepayMoney"
          :label="tableText['realRepayMoney']"
          min-width="150"
        />
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </el-row>
</template>

<script>
import { getAllOverdueFirm, getAllOverdueGroup, getBusinessConfig, urgentRecallAmountDetail, exportUrgentRecallAmountDetail } from '@/api/collection'
import { formatDate } from '@/utils/method'
export default {
  name: 'AmountBreakdown',
  data() {
    return {
      loading: true,
      chType: 1,
      time: [new Date(), new Date()],
      currentTime: null,
      allStage: [],
      allFirm: [],
      allGroup: [],
      tableData: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params()
    }
  },
  mounted() {
    this.tableText = this.$t('collectionManagement.amountBreakdown')
    this.getAllFirm()
    this.getAllStage()
    setTimeout(() => {
      this.getData()
    }, 10)
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        recallDateStart: null,
        recallDateEnd: null,
        currentPeriodRepayDateStart: null,
        currentPeriodRepayDateEnd: null,
        stageId: '',
        overdueDayStart: null,
        overdueDayEnd: null,
        orderNo: null,
        phoneNumber: null,
        dealStatus: '',
        loanProductType: '',
        firmId: '',
        groupId: null,
        staffName: null,
        username: null
      }
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.time = [new Date(), new Date()]
      this.currentTime = null
      this.searchForm = this.params()
      this.getData()
    },
    changeStatus(type) {
      this.chType = type
      this.getData()
    },
    searchData() {
      const data = {
        recallDateStart: this.searchForm.recallDateStart,
        recallDateEnd: this.searchForm.recallDateEnd,
        currentPeriodRepayDateStart: this.searchForm.currentPeriodRepayDateStart,
        currentPeriodRepayDateEnd: this.searchForm.currentPeriodRepayDateEnd,
        stageId: this.searchForm.stageId,
        overdueDayStart: this.searchForm.overdueDayStart,
        overdueDayEnd: this.searchForm.overdueDayEnd,
        orderNo: this.searchForm.orderNo,
        phoneNumber: this.searchForm.phoneNumber,
        dealStatus: this.searchForm.dealStatus,
        staffName: this.searchForm.staffName,
        pageSize: this.searchForm.pageSize,
        currentPage: this.searchForm.currentPage
      }
      if (this.time && this.time.length > 1) {
        data['recallDateStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['recallDateEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['recallDateStart'] = null
        data['recallDateEnd'] = null
      }
      if (this.currentTime && this.currentTime.length > 1) {
        data['currentPeriodRepayDateStart'] = formatDate(new Date(this.currentTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['currentPeriodRepayDateEnd'] = formatDate(new Date(this.currentTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['recallDateStart'] = null
        data['recallDateEnd'] = null
      }
      if (this.searchForm.firmId !== null) {
        data['firmIdList'] = [this.searchForm.firmId]
      }
      if (this.searchForm.groupId !== null) {
        data['groupIdList'] = [this.searchForm.groupId]
      }
      if (this.searchForm.loanProductType !== null) {
        data['loanProductTypeList'] = [this.searchForm.loanProductType]
      }
      return data
    },
    getData() {
      this.loading = true
      urgentRecallAmountDetail(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    exportList() {
      exportUrgentRecallAmountDetail(this.searchData())
    },
    setValue(val, data) {
      console.log(this.$t(`${data}`))
      const name = this.$t(`${data}`).filter(item => {
        return item.value === val
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    getAllFirm() {
      getAllOverdueFirm()
        .then(res => {
          if (res.success) {
            this.allFirm = res.data
            const obj = [{
              firmName: this.$t('common.all'),
              id: ''
            }]
            this.allFirm = obj.concat(this.allFirm)
            this.getAllGroup()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllGroup() {
      getAllOverdueGroup()
        .then(res => {
          if (res.success) {
            const arr = []
            res.data.map(item => {
              if (!arr.includes(item['firmId'])) {
                arr.push(item['firmId'])
              }
            })
            const group = []
            if (arr.length > 0) {
              arr.forEach(v => {
                const options = []
                const a = res.data.filter(item => {
                  return item['firmId'] === v
                })
                a.forEach(item => {
                  options.push(
                    {
                      label: item['groupName'],
                      value: item['id']
                    }
                  )
                })
                const name = this.allFirm.filter(aa => {
                  return aa['id'] === v
                })
                const firmName = name && name[0] && name[0]['firmName'] ? name[0]['firmName'] : 0
                group.push({
                  label: firmName,
                  value: firmName,
                  options
                })
              })
            }
            this.allGroup = group
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllStage() {
      const data = {
        isPage: false
      }
      getBusinessConfig(data)
        .then(res => {
          if (res.success) {
            this.allStage = res.data.filter(item => {
              return item['state'] === 'ACTIVATE'
            })
            const obj = [{
              phaseName: this.$t('common.all'),
              id: ''
            }]
            this.allStage = obj.concat(this.allStage)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    test(data) {
      let value = this.searchForm[data]
      if (value.length > 0) {
        value = value.replace(/[^0-9]/g, '')
      }
      this.searchForm[data] = value
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
